package cn.hackcloud.concurrency.eda;

public class EventDispatcherExample {
    //用于在Channel中的运算
    static class InputEvent extends Event {
        private final int x;
        private final int y;

        InputEvent(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }
    }

    //用于存放结果
    static class ResultEvent extends Event {
        private final int result;

        ResultEvent(int result) {
            this.result = result;
        }

        public int getResult() {
            return result;
        }
    }

    static class ResultEventHandler implements Channel<ResultEvent> {

        @Override
        public void dispatch(ResultEvent message) {
            System.out.println("The result is:" + message.getResult());
        }
    }

    //InputEventHandler向Router发送Event，因此构造时需要传入Dispatcher.
    static class InputEventHandler implements Channel<InputEvent> {
        private final EventDispatcher dispatcher;

        InputEventHandler(EventDispatcher dispatcher) {
            this.dispatcher = dispatcher;
        }

        //将计算的结果构造成新的Event提交给Router
        @Override
        public void dispatch(InputEvent message) {
            int result = message.getX() + message.getY();
            dispatcher.dispatch(new ResultEvent(result));
        }
    }

    public static void main(String[] args) {
        EventDispatcher dispatcher = new EventDispatcher();
        dispatcher.registerChannel(InputEvent.class, new InputEventHandler(dispatcher));
        dispatcher.registerChannel(ResultEvent.class, new ResultEventHandler());
        dispatcher.dispatch(new InputEvent(1, 2));
    }
}
